<template>
	<!-- 供应商-供应商列表 -->
	<div>
		<!-- 供应商-供应商列表 -->
		<Card :bordered="false" dis-hover class="ivu-mt" :padding="0">
			<Form inline class="formValidate mt20" :label-width="80" @submit.native.prevent>
				<FormItem label="搜索：" label-for="store_name">
					<Input placeholder="请输入供应商名称" v-model="keywords" class="input-add" />
					<!-- <Input placeholder="请输入主营产品" v-model="formValidate.sales_type" class="input-add" /> -->
					<Input placeholder="请输入供应商代码" v-model="formValidate.code" class="input-add" />
					<Select placeholder="招商员筛选" v-model="formValidate.admin_id" filterable class="input-add" clearable>
						<Option v-for="item in adminList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
					<Select placeholder="产品位置" v-model="formValidate.position_id" filterable class="input-add" :label-in-value="true" clearable @on-change="(val) => handleSelectChange(val)">
						<Option v-for="item in positionList" :value="item.value" :key="item.value">{{ item.label }}</Option>
					</Select>
					<Select placeholder="佣金类型" v-model="formValidate.house_type" filterable class="input-add" clearable>
						<Option v-for="item in houseType" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
					<Select placeholder="状态" v-model="formValidate.status" filterable class="input-add" clearable>
						<Option v-for="item in statusList" :value="item.value" :key="item.value">{{ item.label }}
						</Option>
					</Select>
					<div class="input-add ivu-input-wrapper ivu-input-wrapper-default ivu-input-type-text">
						<Cascader placeholder="国家地区筛选" :data="addresData" :load-data="loadData" class="input-add"
							v-model="formValidate.addressSelect" @on-change="addchack" change-on-select clearable>
						</Cascader>
					</div>
					<Button type="primary" @click="searchList()">查询</Button>
				</FormItem>
			</Form>
		</Card>

		<Card :bordered="false" dis-hover class="ivu-mt">
			<!-- 操作 -->
			<Button type="primary" class="btn" @click="addSupplier"
				v-auth="['admin-supplier-supplierAdd']">添加供应商</Button>
			<!-- 表格 -->
			<Table :columns="columns" :data="tabList" ref="table" highlight-row max-height="550" no-data-text="暂无数据"
				no-filtered-data-text="暂无筛选结果" class="orderData ivu-mt">
				<!-- 状态 -->
				<template slot-scope="{ row, index }" slot="status">
					<div v-if="row.status==0">审核中</div>
					<div v-if="row.status==1">开户成功</div>
					<div v-if="row.status==2">发货中</div>
					<div v-if="row.status==3">发货成功</div>
				</template>
				<template slot-scope="{ row, index }" slot="type">
					<div v-if="row.type==1">A类账户</div>
					<div v-if="row.type==2">B类账户</div>
				</template>
				<template slot-scope="{ row, index }" slot="house_type">
					<div v-if="row.house_type==1">5%佣金</div>
					<div v-if="row.house_type==2">10%佣金</div>
				</template>
        <template slot-scope="{ row, index }" slot="warehouse_type">
          <div v-if="row.warehouse_type==0">标准版</div>
          <div v-if="row.warehouse_type==1">30天免仓版</div>
        </template>
        <template slot-scope="{ row, index }" slot="type">
          <div v-if="row.type==1">A类</div>
          <div v-if="row.type==2">B类</div>
        </template>



				<!-- 操作 -->
				<template slot-scope="{ row, index }" slot="action">
					<!--          <a @click="goSupplier(row)">进入</a>-->
					<!--          <Divider type="vertical" />-->
          <!-- <a @click="supplierOneLogin(row)" v-auth="['admin-supplier-one-login']">一键登录</a>
          <Divider type="vertical" v-auth="['admin-supplier-one-login']" /> -->
					<a @click="showFollowUpDetail(row)" v-auth="['system_supplier_genjin']">跟进员</a>
					<Divider type="vertical" v-auth="['system_supplier_genjin']" />
					<a @click="getSupplierAgreement(row)" v-auth="['admin-supplier-supplier-agreement-List']">合同</a>
					<Divider type="vertical" v-auth="['admin-supplier-supplier-agreement-List']" />
					<a @click="editWarehouseExhibition(row)" v-auth="['admin-supplier-zhanwei']">展位</a>
					<Divider type="vertical" v-auth="['admin-supplier-zhanwei']" />
					<a @click="edit(row)" v-auth="['admin-supplier-supplierAdd']">编辑</a>
					<Divider type="vertical" v-auth="['admin-supplier-supplierAdd']"/>
<!--					<a @click="del(row, '删除供应商（同步删除商品）', index)" v-auth="['admin-supplier-delete']">删除</a>-->
<!--					<Divider type="vertical" v-auth="['admin-supplier-delete']"/>-->
					<a @click="reset(row)" v-auth="['admin-supplier-resetPwd']">重置密码</a>
				</template>
				<!-- no-data-text="暂无数据" highlight-row -->
				<!-- no-filtered-data-text="暂无筛选结果" -->
			</Table>
			<div>
				<!-- 分页 -->
				<div class="acea-row row-right page">
					<Page :total="page.total" :current="page.pageNum" show-elevator show-total @on-change="pageChange"
						:page-size="page.pageSize" @on-page-size-change="limitChange" />
				</div>
			</div>
		</Card>
		<menus-from :formValidate="formValidate" ref="menusFrom"></menus-from>

		<Modal v-model="followUpModalVisible" title="跟进员列表" :footer-hide="true" width="800">
			<Table ref="followUpTable" :columns="followUpColumns" :data="followUpData"
				@on-current-change="handleRowSelect" highlight-row></Table>

			<!-- 分页 -->
			<div class="acea-row row-right page">
				<Page :total="page1.total" :current="page1.pageNum" show-elevator show-total :page-size="page1.pageSize"
					@on-change="pageChange1" @on-page-size-change="limitChange" />
			</div>

			<!-- 底部按钮 -->
			<div class="modal-footer" style="text-align: right; margin-top: 20px;">
				<Button type="default" @click="followUpModalVisible = false">取消</Button>
				<Button type="primary" @click="submitFollowUp">确认</Button>
			</div>
		</Modal>

	</div>
</template>
<script>
	import {
		mapState
	} from 'vuex'
	import util from '@/libs/util'
	import Setting from '@/setting'
  import {
    supplierList,
    putSupplierStatus,
    supplierLogin,
    getSystemAdminList,
    getDefaultFollowIdApi,
    setFollowDataApi,
    getSupplierAdminListApi, getSupplier,
  } from '@/api/supplier'
	import {
		areaInfoApi
	} from '@/api/store'
	import menusFrom from "./components/menusFrom";
	import {
		findStoreWarehouseExhibition
	} from "@api/warehouseExhibition";
	export default {
		name: '',
		components: {
			menusFrom
		},
		props: {},
		data() {
			return {
				positionList: [{
						value: 1,
						label: '卧室',
					},
					{
						value: 2,
						label: '客厅',
					}
				],
				adminList: [],
				addresData: [],
				houseType: [{
					value: 1,
					label: "5%佣金"
				}, {
					value: 2,
					label: "10%佣金"
				}],
				statusList: [{
					value: 0,
					label: "审核中"
				}, {
					value: 1,
					label: "开户成功"
				}, {
					value: 2,
					label: "发货中"
				}, {
					value: 3,
					label: "发货成功"
				}],
				roterPre: Setting.roterPre,
				keywords: '',
				keywords1: '',
				BaseURL: '',
				followUpModalVisible: false,
				followUpData: [],
				followUpColumns: [{
						title: 'ID',
						key: 'id',
						width: 80
					},
					{
						title: '姓名',
						key: 'real_name'
					},
					{
						title: '手机号',
						key: 'phone'
					}
				],
				selectedFollowUp: null,
				defaultFollowUpId: 0,
				formFollowData: {
					selected_follow_up: 0,
					supplier_id: 0,
				},
				formValidate: {
					position_id:0,
					position_name:"",
					code: "",
					status: -1,
					house_type: 0,
					admin_id: 0,
					sales_type: "",
					province: 0,
					city: 0,
					area: 0,
					street: 0,
				},
				loading: false,
				page1: {
					total: 0, // 总条数
					pageNum: 1, // 当前页
					pageSize: 15, // 每页显示条数
				},
				page: {
					total: 0, // 总条数
					pageNum: 1, // 当前页
					pageSize: 15, // 每页显示条数
				},
				columns: [
          //   {
					// 	title: 'ID',
					// 	key: 'id',
					// 	minWidth: 40,
					// },
					{
						title: '账户类型',
						slot: 'type',
						minWidth: 80,
					},
					{
						title: '招商员',
						key: 'real_name',
						minWidth: 80,
					},
					{
						title: '跟进员',
						key: 'follow_name',
						minWidth: 80,
					},
					{
						title: '产品位置',
						key: 'product_position',
						minWidth: 80,
					},
					{
						title: '供应商代码',
						minWidth: 100,
						key: 'code',
					},
          {
            title: '类型',
            key: 'type',
            slot: 'type',
            minWidth: 100,
          },
					{
						title: '供应商名称',
						minWidth: 100,
						key: 'supplier_name',
					},
					{
						title: '联系人姓名',
						key: 'name',
						minWidth: 100,
					},
					{
						title: '联系方式',
						key: 'phone',
						minWidth: 100,
					},
          {
            title: '仓储类型',
            key: 'warehouse_type',
            slot: 'warehouse_type',
            minWidth: 100,
          },
					{
						title: '佣金类型',
						key: 'house_type',
						slot: 'house_type',
						minWidth: 100,
					},
					{
						title: '邮箱',
						key: 'email',
						minWidth: 100,
					},
					{
						title: '国家地区',
						key: 'area_name',
						minWidth: 100,
					},
					{
						title: '状态',
						slot: 'status',
						minWidth: 100,
					},
					{
						title: '备注',
						key: 'mark',
						minWidth: 300, // 适当调整宽度
						render: (h, {
							row
						}) => {
							return h(
								'Tooltip', {
									props: {
										content: '', // 不使用默认 content，改为 slot
										placement: 'top',
									},
									scopedSlots: {
										content: () => h(
											'div', {
												style: {
													maxHeight: '200px', // 限制高度
													overflowY: 'auto',
													maxWidth: '600px', // 可选：防止一行过长
													whiteSpace: 'pre-wrap', // 换行
												}
											},
											row.mark || '暂无mark'
										)
									}
								},
								[h('span', {
									style: {
										display: 'inline-block',
										maxWidth: '200px',
										whiteSpace: 'nowrap',
										overflow: 'hidden',
										textOverflow: 'ellipsis',
									}
								}, row.mark || '暂无备注')]
							)
						}
					},
					// {
					// 	title: '备注',
					// 	key: 'mark',
					// 	minWidth: 100,
					// },
					{
						title: '操作',
						slot: 'action',
						minWidth: 150,
					},
				],
				tabList: [],
			}
		},
		computed: {
			...mapState('admin/layout', ['isMobile']),
			labelWidth() {
				return this.isMobile ? undefined : 80
			},
			labelPosition() {
				return this.isMobile ? 'top' : 'right'
			},
		},
		watch: {},
		created() {
			this.getSupplier()
			this.getAdminList()
		},
		mounted() {
			let data = {
				pid: 0,
				id: 1
			}
			this.cityInfo(data)
		},
		methods: {
			handleSelectChange(val) {
				console.log(val)
				if(val == undefined){
					this.formValidate.position_name = ""
				}else{
					// 去掉所有回车、换行、制表符，并把多余的空格压缩成一个
					   this.formValidate.position_name = val.label
					       .replace(/[\r\n\t]/g, '') // 去掉回车、换行、Tab
					       .replace(/\s+/g, '');     // 去掉所有空白（如果想保留单词间的空格，这里改成 ' '）
				}
			},
			getAdminList() {
				getSupplierAdminListApi()
					.then(async (res) => {
						this.adminList = res.data.list
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},
			// 获取省市区
			cityInfo(data) {
				areaInfoApi(data).then((res) => {
					this.addresData = res.data
				})
			},
			loadData(item, callback) {
				item.loading = true
				areaInfoApi({
					pid: item.value
				}).then((res) => {
					item.children = res.data
					item.loading = false
					callback()
				})
			},
			// 选择省市区
			addchack(e, selectedData) {
				if (!e || e.length === 0) {
					this.formValidate.province = 0;
					this.formValidate.city = 0;
					this.formValidate.area = 0;
					this.formValidate.street = 0;
				} else {
					e.forEach((i, index) => {
						if (index == 0) {
							this.formValidate.province = i
						} else if (index == 1) {
							this.formValidate.city = i
						} else if (index == 2) {
							this.formValidate.area = i
						} else {
							this.formValidate.street = i
						}
					})
					let addressInfo = [];
					selectedData.forEach(item => {
						addressInfo.push(item.label)
					})
					this.formValidate.address = addressInfo.join('');
				}

			},
      supplierOneLogin(row){
        getSupplier(row.id)
            .then(async (res) => {
              const link = document.createElement('a');
              link.href = Setting.thisUrl+"/supplier/login?user="+res.data.account+"&pwd="+res.data.pwd+"&isvoluns=true";
              link.target = '_blank';  // 关键：指定在新标签页打开
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link); // 清理创建的元素
            })
            .catch((res) => {
              this.$Message.error(res.msg)
            })
      },
			showFollowUpDetail(row) {
				this.followUpModalVisible = true;
				this.formFollowData.supplier_id = row.id;
				this.getDefaultFollowId(row);
			},
			getDefaultFollowId(row) {
				getDefaultFollowIdApi(row.id)
					.then((res) => {
						this.defaultFollowUpId = res.data.id;
						this.findRecord(); // 拿到列表后再处理选中逻辑
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},

			findRecord() {
				let data = {
					keywords: this.keywords1,
					page: this.page1.pageNum,
					limit: this.page1.pageSize,
				};
				console.log(data)
				getSystemAdminList(data)
					.then((res) => {
						this.followUpData = res.data.list;
						this.page1.total = res.data.count;
						this.followUpData = res.data.list.map(item => {
							return {
								...item,
								_highlight: item.id === this.defaultFollowUpId, // ⭐ 默认选中项
							};
						});

					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			handleRowSelect(currentRow) {
				this.selectedFollowUp = currentRow.id;
				this.formFollowData.selected_follow_up = currentRow.id
				// this.selectedFollowUp = currentRow;
			},

			// 提交
			submitFollowUp() {
				if (!this.selectedFollowUp) {
					this.$Message.warning('请选择一名跟进员');
					return;
				}
				// 提交逻辑
				console.log('选择的跟进员：', this.selectedFollowUp);

				// 提交后关闭弹窗
				this.followUpModalVisible = false;
				console.log("---------", this.formFollowData)
				if (this.formFollowData.selected_follow_up && this.formFollowData.supplier_id) {
					setFollowDataApi(this.formFollowData)
						.then(async (res) => {
							this.$Message.success("保存成功")
							this.$router.push({
								path: this.roterPre + '/supplier/menu/list'
							})
							this.getSupplier()
						})
						.catch((res) => {
							this.$Message.error(res.msg)
						})
				}
			},

			formatDate(value) {
				console.log("value:", value)
				if (!value) return '';
				const date = new Date(value);

				// 方法 2（更灵活）：手动格式化
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			// 编辑展位
			editWarehouseExhibition(row) {
				findStoreWarehouseExhibition(row.id).then((res) => {
					this.formValidate = res.data;
					this.formValidate.warehouse_id = '3'
					this.$refs.menusFrom.modals = true;
					this.$refs.menusFrom.titleFrom = "编辑展位";
					this.$refs.menusFrom.clickRadio(3)
				}).catch((res) => {
					this.$Message.error(res.msg);
				});


			},
			addSupplier() {
				this.$router.push({
					path: this.roterPre + '/supplier/supplierAdd'
				})
			},
			getSupplierAgreement(row) {
				this.$router.push({
					path: this.roterPre + '/supplier/supplier-agreement/list/' + row.id
				})
			},
			pageChange1(index) {
				this.page1.pageNum = index
				this.findRecord();
			},
			pageChange(index) {
				this.page.pageNum = index
				this.getSupplier()
			},
			limitChange1(limit) {
				this.page1.pageSize = limit
				this.findRecord()
			},
			limitChange(limit) {
				this.page.pageSize = limit
				this.getSupplier(row)
			},
			searchList() {
				this.page.pageNum = 1
				this.page.pageSize = 15
				this.getSupplier()
			},
			// 获取供应商列表
			getSupplier() {
				// alert(this.formValidate.status)
				if (this.formValidate.status == undefined) {
					this.formValidate.status = -1
				}
				let data = {
					code: this.formValidate.code,
					house_type: this.formValidate.house_type,
					status: this.formValidate.status,
					admin_id: this.formValidate.admin_id,
					province: this.formValidate.province,
					city: this.formValidate.city,
					area: this.formValidate.area,
					sales_type: this.formValidate.sales_type,
					position_name:this.formValidate.position_name,
					keywords: this.keywords,
					page: this.page.pageNum, // 当前页
					limit: this.page.pageSize, // 每页显示条数
				}
				supplierList(data)
					.then(async (res) => {
						this.tabList = res.data.list
						this.page.total = res.data.count
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},

			// 编辑
			edit(row) {
				this.$router.push({
					path: this.roterPre + '/supplier/supplierAdd/' + row.id
				})
			},

			// 修改状态
			onchangeIsShow(row) {
				putSupplierStatus(row.id, row.is_show)
					.then(async (res) => {
						this.$Message.success(res.msg)
					})
					.catch((res) => {
						this.$$Message.error(res.msg)
					})
			},

			// 进入供应商
			goSupplier(row) {
				supplierLogin(row.id)
					.then(async (res) => {
						let data = res.data
						let expires = data.expires_time
						util.cookies.setSupplier('token', data.token, {
							expires: expires,
						})
						util.cookies.setSupplier('uuid', data.user_info.id, {
							expires: expires,
						})
						util.cookies.setSupplier('expires_time', expires, {
							expires: expires,
						})
						util.cookies.setSupplier('pageTitle', row.supplier_name);
						util.makeMenu(`/${data.prefix}`, data.menus)
						let storage = window.localStorage
						storage.setItem('menuListSupplier', JSON.stringify(data.menus))
						storage.setItem(
							'uniqueAuthSupplier',
							JSON.stringify(data.unique_auth)
						)
						let userInfoSupplier = {
							account: data.user_info.account,
							head_pic: data.user_info.avatar,
							logo: data.logo,
							logoSmall: data.logo_square,
							version: data.version,
						}
						storage.setItem('userInfoSupplier', JSON.stringify(userInfoSupplier))
						this.BaseURL = Setting.apiBaseURL.replace(/adminapi/, `${row.prefix}/home/`);
						window.open(this.BaseURL)
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},

			// 删除
			del(row, tit, num) {
				let data = {
					ids: row.id,
				}
				let delfromData = {
					title: tit,
					num: 0,
					url: `/supplier/deleteSystemSupplier`,
					method: 'DELETE',
					ids: data,
				}
				this.$modalSure(delfromData)
					.then((res) => {
						this.$Message.success(res.msg)
						this.tabList.splice(num, 1);
						if (!this.tabList.length) {
							this.page.pageNum =
								this.page.pageNum == 1 ? 1 : this.page.pageNum - 1;
						}
						this.getSupplier()
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			},
			// 重置密码
			reset(row) {
				let data = {
					id: row.id,
				}
				let delfromData = {
					title: "重置密码",
					num: 0,
					url: `/supplier/reset_supplier_pwd/${row.id}`,
					method: 'POST',
					// data: { id: row.id },
				}
				this.$modalSure(delfromData)
					.then((res) => {
						this.$Message.success(res.msg)
					})
					.catch((res) => {
						this.$Message.error(res.msg)
					})
			}
		},
	}
</script>
<style scoped lang="less">
	.input-add {
		width: 250px;
		margin-right: 14px
	}

	.btn {
		margin: 0 0 10px 0px;
	}

	.del {
		margin-left: 10px;
	}

	// .card {
	//   margin-top: 15px;
	// }
	.ivu-form-inline {
		padding-top: 20px;
	}
</style>